<template>
  <div class="app-container">
    <!--查询  -->
    <el-row>
      <el-input style="width:200px;margin-right: 10px" v-model="tableQuery.name" placeholder="用户名" v-perm="['user-search']"></el-input>
      <el-tooltip class="item-sh" content="搜索" placement="top" >
        <el-button icon="el-icon-search" circle @click="fetchData(1)" v-perm="['user-search']"></el-button>
      </el-tooltip>
    </el-row>
    <div style="margin-bottom: 30px;"></div>
    <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleCreate" v-perm="['user-insert']">{{textMap.create}}</el-button>
    <div style="margin-bottom: 30px;"></div>
    <!--列表-->
    <el-table style="width: 100%"
              :data="tableData"
              v-loading.body="tableLoading"
              element-loading-text="加载中"
              border fit highlight-current-row>
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="mobile" label="账号"></el-table-column>
      <el-table-column prop="name" label="名称"></el-table-column>
      <el-table-column prop="type_name" label="用户类型">
        <template slot-scope="scope">
          <el-tag type="success" v-for="user in userTypes" :key="user.id" v-if="user.key==scope.row.type">{{user.name}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="created_at" label="创建时间"></el-table-column>
      <el-table-column label="操作"  width="150">
        <template slot-scope="scope">
          <el-tooltip content="账号信息编辑" placement="top">
            <el-link icon="el-icon-edit" @click="handleUpdate(scope.$index,scope.row)" v-perm="['user-update']">编辑</el-link>
          </el-tooltip>
          <span style="margin:10px" v-perm="['user-update']">|</span>
          <el-dropdown @command="handleCommand">
            <span class="el-dropdown-link">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="{label:'organize',data:scope.row,index:scope.$index}" :disabled="scope.row.type==='admin'" v-perm="['user-orgnize']">组织</el-dropdown-item>
              <el-dropdown-item :command="{label:'role',data:scope.row,index:scope.$index}" :disabled="scope.row.type==='admin'" v-perm="['user-assign-role']">角色</el-dropdown-item>
              <el-dropdown-item :command="{label:'delete',data:scope.row,index:scope.$index}" :disabled="scope.row.type==='admin'" v-perm="['user-delete']">删除</el-dropdown-item>
              <el-dropdown-item :command="{label:'reset',data:scope.row,index:scope.$index}" :disabled="scope.row.type==='admin'" v-perm="['user-reset-passpord']">重置密码</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-bottom: 30px;"></div>
    <!--分页-->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="tablePage.current"
      :page-sizes="[20, 30, 40, 50, 60]"
      :page-size="tablePage.size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tablePage.total">
    </el-pagination>
    <!--弹出窗口：新增/编辑用户-->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="80%">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="left" label-width="120px">
        <el-form-item label="ID" prop="id" v-if="dialogStatus=='update'">
          <el-input v-model="temp.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="mobile">
          <el-input v-model="temp.mobile" placeholder="用户登录账号"></el-input>
        </el-form-item>
        <el-form-item label="用户描述" prop="desc">
          <el-input v-model="temp.desc"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="temp.email"></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name" placeholder="请输入用户名称"></el-input>
        </el-form-item>
        <el-form-item label="地区" prop="area">
          <el-input v-model="temp.area"></el-input>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="temp.address"></el-input>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="temp.type" placeholder="请选择用户类型">
            <el-option v-for="(item,index) in userTypes" :key="index" :label="item.name" :value="item.key" :disabled="item.disabled"/>
          </el-select>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch v-model="isopen" active-text="开启" inactive-text="关闭"></el-switch>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">创建</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
    <!--弹出窗口：修改用户角色-->
    <el-dialog title="修改用户的角色" :visible.sync="editRolesDialogVisible" width="60%" @close="optionDialogClosed">
      <div>
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="checkAllRoles">全选</el-checkbox>
        <div style="margin: 15px 0;"></div>
        <el-checkbox-group v-model="updateUserRolesData.roles">
          <el-checkbox class="role-checkbox" v-for="role in roleOptions" :label="role.id" :key="role.id">
            {{role.name}}
          </el-checkbox>
        </el-checkbox-group>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="checkUpdateUserRolesData">确定</el-button>
      </div>
    </el-dialog>
    <!--弹出窗口：修改用户组织-->
    <el-dialog title="修改用户组织" :visible.sync="editOrgsDialogVisiable" @close="orgnizeDialogClosed" width="80%">
      <el-container class="tenant-container">
        <el-main class="tenant-main">
          <el-card class="box-card">
            <div slot="header">
              <div class="title-box" style="padding-top: 10px; padding-bottom: 13px;">
                <span>组织选择</span>
              </div>
            </div>
            <el-input class="mgb-15" :placeholder="filterPlaceholderText" v-model="filterOrgText"></el-input>
            <div style="margin-bottom: 10px;"></div>
            <el-tree ref="OrganizeTreeRef" :filter-node-method="filterNode" :data="orgnizeOptions"
                     :props="treeProps" node-key="id" default-expand-all  show-checkbox>
              <span class="custom-tree-node" slot-scope="{ node, data }">
                  <span>
                    <span v-if="data.type==OrgnizeType.ANCESTOR" class="mgl-10"><span class="tenant-title">{{ data.name }}</span><el-tag class="mgl-10" type="info" size="mini">集团</el-tag></span>
                    <span v-else-if="data.type==OrgnizeType.AREA" class="mgl-10"><span class="tenant-title">{{ data.name }}</span><el-tag class="mgl-10" type="info" size="mini">区域</el-tag></span>
                    <span v-else-if="data.type==OrgnizeType.FACTORY" class="mgl-10"><span class="company-title">{{ data.name }}</span><span v-if="data.sub_title">({{ data.sub_title }})</span><el-tag class="mgl-10" type="info" size="mini">公司</el-tag></span>
                    <span v-else-if="data.type==OrgnizeType.DEPARTMENT" class="mgl-10"><span class="department-title">{{ data.name }}</span><el-tag class="mgl-10" type="info" size="mini">部门</el-tag></span>
                  </span>
              </span>
            </el-tree>
          </el-card>
        </el-main>
      </el-container>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editOrgsDialogVisiable = false">取消</el-button>
        <el-button type="primary" @click="checkUpdateOrgnizeData">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import userApi from '@/api/user'
  import orgnizeApi from '@/api/orgnization'
  import {parseTime, resetTemp} from '@/utils'
  import {confirm,OrgnizeType,userTypes} from '@/utils/constants'
  import debounce from 'lodash/debounce'

  export default {

    name: 'UserManage',
    data() {
      return {
        parseTime: parseTime,
        tableLoading: false,
        tableData: [],
        tableQuery: {
          name: null,
          roleid:null
        },
        tablePage: {
          current: null,
          pages: null,
          size: null,
          total: null
        },
        dialogFormVisible: false,
        editRolesDialogVisible: false,
        editOrgsDialogVisiable:false,
        checkedKeys:[],
        dialogStatus: '',
        userTypes,
        OrgnizeType,
        temp: {
          idx: null, //tableData中的下标
          id: null,
          name: null,
          email: null,
          desc: null,
          mobile: null,
          area: null,
          address: null,
          isopen:null,
          type:null,
          preferences:null,
          member_id:null,
          role_name:null,
          orgnization_name:null,
          roles:null,
          orgnizations:null,
          created_at:null,
          updated_at:null
        },
        textMap: {
          update: '编辑用户',
          create: '新增用户'
        },
        rules: {
          name:[{required: true, message: '请输用户名称', trigger: 'blur'}],
          mobile: [{ required: true, message: '必填', trigger: 'blur' }]
        },
        isopen:true,
        checkAll: false,
        isIndeterminate: true,
        filterPlaceholderText: '输入组织名称过滤',
        filterOrgText:'',
        treeProps:{
          label:'name',
          children:'children'
        },
        //所有角色(管理员除外)
        roleOptions:[],
        // 更新用户的角色的数据
        updateUserRolesData: {
          idx: null,
          id: null,
          roles: []
        },
        orgnizeOptions:[],
        updateUserOrgData: {
          idx: null,
          id: null,
          orgnizations: []
        },
      }

    },
    created() {
      this.initData()
    },
    watch: {
      //延时查询
      'tableQuery.name': debounce(function () {
        this.fetchData()
      }, 500),
      'filterOrgText': debounce(function (val) {
        this.$refs.OrganizeTreeRef.filter(val);
      }, 600),
    },//watch

    methods: {
      initData(){
        orgnizeApi.orgnizeTree().then(res=>{
          this.orgnizeOptions=res.data
          this.fetchData()
        })
      },

      hasAdminRole(row){
        return true
      },

      //全选
      checkAllRoles(val) {
        let allRids = this.roleOptions.map(role => role.id)
        this.updateUserRolesData.roles = val ? allRids : [];
        this.isIndeterminate = false;
      },
      checkAllOrgnizes(val){
        let allOrgs = this.orgnizeOptions.map(org => org.id)
        this.updateUserOrgData.orgnizations = val ? allOrgs : [];
        this.isIndeterminate = false;
      },
      //分页
      handleSizeChange(val) {
        this.tablePage.size = val;
        this.fetchData();
      },
      handleCurrentChange(val) {
        this.tablePage.current = val;
        this.fetchData();
      },
      filterNode(value, data) {
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
      },
      //查询
      fetchData(current) {
        if(current){
          this.tablePage.current = current
        }
        this.tableLoading=true
        userApi.queryUser(this.tableQuery, this.tablePage).then(res => {
          let userdata = res.data
          this.tableData = userdata.data
          this.tablePage.total=userdata.total
          if(!this.tablePage.current)
            this.tablePage.current=1
          if (!this.tablePage.size)
            this.tablePage.size=20
          this.tableLoading = false
        }).catch(err=>{
          this.tableData=[]
          resetTemp(this.tablePage)
          resetTemp(this.tableQuery)
          this.tableLoading=false
        })
      },

      //更新
      handleUpdate(idx, row) {
        if (row.type==='admin'){
          this.$message.error("管理员不可编辑")
          return
        }
        this.temp = Object.assign({}, row) // copy obj
        this.temp.idx = idx
        this.isopen = Boolean(this.temp.isopen)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => this.$refs['dataForm'].clearValidate())
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (!valid) return
          this.temp.isopen = this.isopen?1:0
          const tempData = Object.assign({}, this.temp)//copy obj
          userApi.storeUser(tempData).then(res => {
            this.dialogFormVisible = false
            this.$message.success("更新成功")
            this.fetchData(1)
          })
        })
      },


      //更新用户的角色
      handleUpdateUserRoles(idx, row) {
        userApi.userRole(row.id).then(res=>{
          this.roleOptions = res.data.roles
          this.updateUserRolesData.idx=idx
          this.updateUserRolesData.id=row.id
          this.updateUserRolesData.roles = res.data.myRoles.map(role=>role.id)
        })
        this.editRolesDialogVisible = true
      },

      checkUpdateUserRolesData() {
        const noRolesSelected = this.updateUserRolesData && this.updateUserRolesData.roles && this.updateUserRolesData.roles.length ==0;
        if(noRolesSelected){
          this.$confirm('当前没有选中任何角色，会清除该用户已有的角色, 是否继续?', '提示', confirm).then(() => {
            this.invokeUpdateUserRolesApi()
          }).catch(() => {
            this.$message("已取消编辑用户角色");
          });
        }else{
          this.invokeUpdateUserRolesApi()
        }
      },

      invokeUpdateUserRolesApi(){
        let roles = ''
        if (this.updateUserRolesData.roles.length)
          roles=this.updateUserRolesData.roles.join(',')
        const data = {
          id: this.updateUserRolesData.id,
          roles: roles
        }
        userApi.storeUserRole(data).then(res => {
          this.editRolesDialogVisible = false
          this.$message.success("更新成功")
        })
      },
      //删除
      handleDelete(idx, row) {
        this.$confirm('您确定要永久删除该用户？', '提示', confirm).then(() => {
          userApi.deleteUser({id: row.id}).then(res => {
            this.tablePage.total--
            this.dialogFormVisible = false
            const page_surplus = this.tablePage.total % this.tablePage.size
            const max_page = Math.ceil(this.tablePage.total/this.tablePage.size)
            if (!page_surplus&&this.tablePage.current>max_page)
              this.tablePage.current--
            this.$message.success("删除成功")
            this.fetchData()
          })
        }).catch(() => {
          this.$message.info("已取消删除")
        });

      },

      //新增
      handleCreate() {
        resetTemp(this.temp)
        this.temp.type=userTypes[3].key
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (!valid) return;
          this.temp.isopen=this.isopen?1:0
          userApi.storeUser(this.temp).then((res) => {
            this.dialogFormVisible = false
            this.$message.success("添加成功")
            this.fetchData(1)
          })
        })
      },
      orgnizeDialogClosed(){
        this.checkedKeys=[]
        resetTemp(this.temp)
      },
      handleUpdateOrgnize(idx, row){
        this.editOrgsDialogVisiable=true
        this.temp = Object.assign({},row)
        this.temp.idx = idx
        userApi.userOrgnizes(row.id).then(res=>{
          let aorgs = res.data.orgnizations
          let morgs = res.data.myOrgnizations
          let allkeys = aorgs.map(org=>org.id)
          this.checkedKeys = morgs.map(org=>org.id)
          allkeys.forEach(value=>{
            let ifcheck = this.checkedKeys.indexOf(value)>-1
            this.$refs.OrganizeTreeRef.setChecked(value, ifcheck, false)
          })
        })

      },
      checkUpdateOrgnizeData(){
        this.checkedKeys = this.$refs.OrganizeTreeRef.getCheckedKeys()
        let orgnizations = this.checkedKeys.join(',')
        userApi.storeUserOrgnize(this.temp.id,orgnizations).then(res=>{
          this.$message.success("组织设置成功")
          this.editOrgsDialogVisiable=false
        })
      },
      handleResetUserPwd(idx,row){
        this.$confirm('是否重置该用户的密码?', '提示', confirm).then(()=>{
          const data={
            idstring:row.id
          }
          userApi.resetPwd(data).then(res=>{
            this.$message.success("密码重置成功")
          })
        }).catch(()=>{
          this.$message.info("已取消重置密码")
        })

      },
      optionDialogClosed(){
        this.checkAll=false
        this.isIndeterminate=true
      },
      handleCommand(comand){
        if (comand.label==='delete'){
          this.handleDelete(comand.index,comand.data)
        }else if (comand.label==='organize'){
          this.handleUpdateOrgnize(comand.index,comand.data)
        }else if (comand.label==='role') {
          this.handleUpdateUserRoles(comand.index,comand.data)
        }else {
          this.handleResetUserPwd(comand.index,comand.data)
        }
      }

    }
  }
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
  @import 'src/styles/variables.scss';
  .tenant-title{
    font-weight: normal;
    color:$tenant-color;
  }
  .company-title{
    font-weight: lighter;
    color: $company-color;
    font-size: small;
    margin-right: 10px;
  }
  .department-title{
    font-weight: lighter;
    color: $department-color;
    font-size: small;
  }
  .mgl-10 {
      margin-left: 10px;
    }
  .role-checkbox{
    margin-left: 0px;
    margin-right: 15px;
  }
  .user-oper{
    text-decoration: underline;
    display: inline-block;
    padding: 5px;
    cursor: pointer;
  }
  .user-del{
    color: red;
  }
  .tenant-container{
    height: 500px;
  }
  .box-card {
    width: 100%;
  }
  .tenant-aside{
    width: 40%;
    display: flex;
    align-items: flex-start;
    justify-content: center;
  }
  .tenant-main{
    display: flex;
    width: 100%;
    align-items: flex-start;
    justify-content: center;
  }
  .title-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
    span {
      font-size: 22px;
    }
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
  .mgb-15 {
    margin-bottom: 15px;
  }
  .item-zh{
    margin-left: 100px;
  }
</style>
